<?php
namespace app\api\logic;

use app\common\enum\TaskEnum;
use app\common\logic\BaseLogic;
use app\common\model\task\Task;
use app\common\model\task\TaskList;
use app\common\model\task\TaskReward;
use app\common\model\user\User;
use app\common\service\WeChatService;

class TaskLogic extends BaseLogic{


    public function addTaskList($params){
        
        $models = [];
        $tasks = $params['list'];
        $contents = '';
        if(empty($params['title'])){
            $title = ' ';
            foreach($tasks as $task){   
                $title .= $task.',';
            }
            if(mb_strlen($title) > 255){
                $title = mb_substr($title,0,255);
            }else if($title != ''){
                $title = substr($title,0,strlen($title)-1);
            }
        }else{
            $title = $params['title'];
        }
        foreach($tasks as $task){   
            $contents .= $task.',';
        }
        $riskcheck = WeChatService::riskCheck($title.','.$contents);
        if($riskcheck !== true){
            self::setError('输入内容存在违规!');
            return false;
        }
        $uid = $params['user_id'];
        $listmodel = $this->createTaskList($uid,$title);
        $model = new Task();
        foreach($tasks as $task){
            if(empty($task)) continue;
            $md = [
                'list_id' => $listmodel->id,
                'user_id' => $uid,
                'task' => $task,
                'create_time' => time(),
                'status' => TaskEnum::CREATE,
            ];
            $models[] = $md;
        }
        
        $model->saveAll($models);

        if(!empty($params['reward'])){
            $this->addTaskReward(['task_id'=>$listmodel->id,'user_id'=>$uid,'reward'=>$params['reward']]);
        }


        $list = TaskList::where('id','=',$listmodel->id)
        ->field('id,status,worker_id,user_id,start_time,end_time,share_code,title')
        ->with([
                'tasks'=>function($query){$query->order('id','asc');}, 
                'owner'=>function($query){$query->field('id,nickname,avatar');},
                'reward'=>function($query){$query->field('id,list_id,reward');},

                // 'worker'=>function($query){$query->field('id,nickname,avatar');},
        ])->find();
        
        return $list->toArray();
    }

    public function addTask($params){
        $tasklist_id = $params['task_list_id'];
        $share_code = '';
        if(empty($tasklist_id)){
            $tasklist = $this->createTaskList($params['user_id']);
            $tasklist_id = $tasklist->id;
            $share_code = $tasklist->share_code;
        }
        $model = new Task();
        $model->list_id = $tasklist_id;
        $model->user_id = $params['user_id'];
        $model->task = $params['task'];
        $model->create_time = time();
        $model->start_time = time();
        $model->status = TaskEnum::CREATE;
        $model->save();
        return ['id' => $model->id,'list_id'=>$tasklist_id,'task'=>$model->task,'status'=>$model->status,'share_code'=>$share_code];
    }

    private function createTaskList($user_id,$title=''){
        $model = new TaskList();
        $model->user_id = $user_id;
        if(empty($title)){
            $title = '任务清单：'.date('Y-m-d');
        }
        $model->title = $title;
        $model->status = TaskEnum::LIST_CREATE;
        $model->create_time = time();
        $prefix = 'BS-'.$user_id.'-';
        $model->share_code = uniqid($prefix,true);
        $model->save();
        return $model;
    }


    public function editTask($params){
        $model = Task::get($params['id']);
        $model->task = $params['task'];
        $model->content = $params['content'];
        $model->save();
    }

    /**
     * 已经上线的任务,只能取消
     */
    public function cancelTask($params){
        $model = Task::get($params['id']);
        if(!$this->checkOwner($model,$params)) return false;
        if($model->status != TaskEnum::DOING){
            self::setError('只有进行中的任务才能取消');
            return false;
        }
        $model->status = TaskEnum::CANCEL;
        $model->save();
    }

    /**
     * 未发布的任务可以删除
     */
    public function deleteTask($params){
        $model = Task::where('id',$params['task_id'])->find();
        if(!$this->checkOwner($model,$params)) return false;
        if($model->status != TaskEnum::CREATE){
            self::setError('只有新任务才能删除');
            return false;
        }
        $model->delete();
        return true;
    }

    /**
     * 确认任务
     */
    public function confirmTask($params){
        $model = Task::where('id',$params['task_id'])->find();
        if(!$this->checkOwner($model,$params)) return false;
        if($model->status == TaskEnum::CONFIRM){
            self::setError('已经确认过了');
        }
        $model->status = TaskEnum::CONFIRM;
        $model->save();
        return true;
    }

    public function workingTask($params){
        $model = Task::where('id',$params['task_id'])->find();
        if(!$this->checkOwner($model,$params)) return false;
        if($model->status > TaskEnum::DOING){
            self::setError('已经确认过了');
            return false;
        }
        $model->worker_id = $params['user_id'];
        $model->status = TaskEnum::DOING;
        $model->start_time = time();
        $model->save();
        return true;
    }



    public function completeTask($params){
        $model = Task::where('id',$params['task_id'])->find();
        if(!$this->checkOwner($model,$params)) return false;
        if($model->status > TaskEnum::DOING){
            self::setError('已经确认过了');
            return false;
        }
        $model->worker_id = $params['user_id'];
        $model->status = TaskEnum::COMPLETE;
        $model->complete_time = time();
        $model->save();
        $uncompleteCount = Task::where('list_id','=',$model->list_id)->where('status','<',TaskEnum::COMPLETE)->count();
        if($uncompleteCount==0){
            Tasklist::where('id','=',$model->list_id)->update(['status'=>TaskEnum::LIST_COMPLETE,'end_time'=>time()]);
        }
        //添加经验值
        User::where('id','=',$model->user_id)->whereOr('id','=',$model->worker_id)->inc('exp',10)->update();
        return true;
    }


    public function addTaskReward($params){
        $model = new TaskReward();
        $model->list_id = $params['task_id'];
        $model->user_id = $params['user_id'];
        $model->reward = $params['reward'];
        $model->create_time = time();
        $model->save();
    }
    

    public function myTaskList($user_id){
        $model = new TaskList();
        $list = $model->where('user_id','=',$user_id)->order('id','desc')->select();
        return $list;
    }

    /**
     * 获取最后一次任务
     * 
     * @return Array
     */
    public function temptask($uid){
        $model = new TaskList();
        $tasklist = $model->where('user_id','=',$uid)->order('status','asc')->order('id','desc')->find();
        if(empty($tasklist)){
            return [];
        }
        $list = Task::where('list_id','=',$tasklist['id'])->order('id','asc')->select();
        $tasklist->tasks = $list;
        $data = $tasklist->toArray();
        $data['usermap'] = $this->collectUserInfo([$data]);
        return $data;
    }

    public function collectUserInfo($taskListArray){
        $uidArray = [];
        foreach($taskListArray as $item){
            if(isset($item['worker_id'])){
                $uidArray[] = $item['worker_id'];
            }
            $tasks= $item['tasks'];
            if(is_array($tasks)){
                foreach($tasks as $task){
                    if(isset($task['worker_id'])){
                        $uidArray[] = $task['worker_id'];
                    }
                }
            }
        }
        return $this->getUserList($uidArray);
    }

    private function getUserList($uidArray){
        $map = [];

        if(!empty($uidArray)){
            $model = new User();
            $list = $model->where('id','in',$uidArray)->field('id,nickname,avatar')->select();
            foreach($list as $item){
                $map[$item['id']] = $item;
            }
        }
        return $map;
    }

    private function checkOwner($model,$params){
        if($model->list_id != $params['task_list_id']){
            self::setError('没有权限');
            return false;
        }
        return true;
    }


    /**
     * 查询任务,通过分享码 
     * @param string $share_code
     * @param integer $user_id
    */
    public function queryTaskList($share_code,$user_id){
        $model = TaskList::where('share_code','=',$share_code)->find();
        if(empty($model)){
            self::setError('任务清单不存在');
            return false;
        }

        $user = User::where('id','=',$model->user_id)->find();
        $model->owner = $user;

        $tasks = Task::where('list_id','=',$model->id)->order('id','asc')->select();
        $model->tasks = $tasks;
        return $model->toArray();
    }

    public function joinTaskList($share_code,$user_id){
        $model = TaskList::where('share_code','=',$share_code)->find();
        if(empty($model)){
            self::setError('任务清单不存在');
            return false;
        }
        //接任务
        if($model->status == TaskEnum::LIST_CREATE){
            // 自己的任务清单不接
            if($model->user_id != $user_id){
                $model->status = TaskEnum::LIST_SHARE;
                $model->worker_id = $user_id;
                $model->start_time = time();
                $model->save();
            }
        }else{
            if($model->worker_id != $user_id && $model->user_id != $user_id){
                self::setError('任务清单已经被别人完成');
                return false;
            }
        }
        $user = User::where('id','=',$model->user_id)->find();
        $model->owner = $user;
        $tasks = Task::where('list_id','=',$model->id)->order('id','asc')->select();
        $model->tasks = $tasks;
        return $model->toArray();
    }

    /***
     *  确认接任务,自己接自己的任务
     */
    public function confirmMyTaskList($params){
        $model = TaskList::where('id','=',$params['id'])->find();
        if($model->status == TaskEnum::LIST_CREATE){
            $model->worker_id = $params['user_id'];
            $model->start_time = time();
            $model->save();
        }
        return true;
    }

    /**
     * 获取正在进行的任务清单
    */
    public function workingTaskList($user_id){
        $list = TaskList::where('worker_id','=',$user_id)->where('status','!=',TaskEnum::LIST_COMPLETE)->order('id','desc')
        ->field('id,status,worker_id,user_id,start_time,end_time')
        ->with([
                'tasks'=>function($query){$query->order('id','asc');}, 
                'owner'=>function($query){$query->field('id,nickname,avatar');},
                // 'worker'=>function($query){$query->field('id,nickname,avatar');},
        ])->select();
        return $list->toArray();
    }

    /**
     * 获取我的任务数据,统计我发的任务,我接的任务,完成的任务
    */
    public function myTaskData($user_id){
        $model = new Task();
        $mytask = $model->where('user_id','=',$user_id)->field('status,count(1) as count')->group('status')->select();
        $mywork = $model->where('worker_id','=',$user_id)->field('status,count(1) as count')->group('status')->select();
        function mywork($tasklist){
            $count = 0;
            $complete = 0;
            foreach($tasklist as $task){
                $count += $task['count'];
                if($task['status'] >= TaskEnum::COMPLETE){
                    $complete += $task['count'];
                }
            }
            return ['count'=>$count,'complete'=>$complete];
        }
        
        $list = [
            'mytask'=>mywork($mytask),
            'mywork'=>mywork($mywork)
            
        ];
        $list['total'] = $list['mytask']['count']+$list['mywork']['count'];
        return $list;
    }
    
}